﻿package com.superwindcloud.blackjack

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlin.random.Random


@Composable
fun dealingCardsForDealer(
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>,
    isGameStarted: MutableState<Boolean>,
    dealerInitScore: MutableState<Int>,
    isDealerTurnToAskForCards: MutableState<Boolean>
) {
    // 生成两个随机数
    val lightScore = generateDealerLightCard()
    val lightCard by remember { mutableStateOf(lightScore.value) }
    val darkCard by remember { mutableStateOf(Random.nextInt(1, 14)) }

    // 普通牌, ACE, 皇后牌
    if (isDealerTurnToAskForCards.value == false) {
        Box(modifier = Modifier.fillMaxSize()) {
            // 一张随机排, 一张暗牌
            var lightPainter = painterResource(id = R.drawable.card_back)
            if (lightCard == 1) {
                val randomColor = Random.nextInt(1, 5)
                when (randomColor) {
                    1 -> {
                        lightPainter = painterResource(id = R.drawable.card_clubs_1)
                    }

                    2 -> {
                        lightPainter = painterResource(id = R.drawable.card_hearts_1)
                    }

                    3 -> {
                        lightPainter = painterResource(id = R.drawable.card_spades_1)
                    }

                    4 -> {
                        lightPainter = painterResource(id = R.drawable.card_diamonds_1)
                    }
                }
            } else if (lightCard == 11 || lightCard == 12 || lightCard == 13) {
                when (lightCard) {

                    11 -> {
                        val randomColor = Random.nextInt(1, 5)

                        when (randomColor) {
                            1 -> {
                                lightPainter = painterResource(id = R.drawable.card_hearts_11)
                            }

                            2 -> {
                                lightPainter = painterResource(id = R.drawable.card_spades_11)
                            }

                            3 -> {
                                lightPainter = painterResource(id = R.drawable.card_diamonds_11)
                            }

                            4 -> {
                                lightPainter = painterResource(id = R.drawable.card_clubs_11)
                            }
                        }
                    }

                    12 -> {


                        val randomColor = Random.nextInt(1, 5)
                        when (randomColor) {
                            1 -> {
                                lightPainter = painterResource(id = R.drawable.card_clubs_12)
                            }

                            2 -> {
                                lightPainter = painterResource(id = R.drawable.card_hearts_12)
                            }

                            3 -> {
                                lightPainter = painterResource(id = R.drawable.card_spades_12)
                            }

                            4 -> {
                                lightPainter = painterResource(id = R.drawable.card_diamonds_12)
                            }
                        }
                    }

                    13 -> {
                        val randomColor = Random.nextInt(1, 5)
                        when (randomColor) {
                            1 -> {
                                lightPainter = painterResource(id = R.drawable.card_hearts_13)
                            }

                            2 -> {
                                lightPainter = painterResource(id = R.drawable.card_spades_13)
                            }

                            3 -> {
                                lightPainter = painterResource(id = R.drawable.card_diamonds_13)
                            }

                            4 -> {
                                lightPainter = painterResource(id = R.drawable.card_clubs_13)
                            }
                        }


                    }
                }

            } else {
                val randomColor = Random.nextInt(1, 5)
                when (randomColor) {
                    1 -> {
                        val str = "card_clubs_" + lightCard.toString()

                        val context = LocalContext.current
                        val resId = context.resources.getIdentifier(str, "drawable", context.packageName)
                        if (resId != 0) lightPainter = painterResource(id = resId)
                    }

                    2 -> {
                        val str = "card_hearts_" + lightCard.toString()

                        val context = LocalContext.current
                        val resId = context.resources.getIdentifier(str, "drawable", context.packageName)
                        if (resId != 0) lightPainter = painterResource(id = resId)
                    }

                    3 -> {
                        val str = "card_spades_" + lightCard.toString()

                        val context = LocalContext.current
                        val resId = context.resources.getIdentifier(str, "drawable", context.packageName)
                        if (resId != 0) lightPainter = painterResource(id = resId)
                    }

                    4 -> {
                        val str = "card_diamonds_" + lightCard.toString()

                        val context = LocalContext.current
                        val resId = context.resources.getIdentifier(str, "drawable", context.packageName)
                        if (resId != 0) lightPainter = painterResource(id = resId)
                    }
                }
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.Center)
                    .offset(y = (-100).dp)
                    .padding(16.dp), horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (lightCard == 11 || lightCard == 12 || lightCard == 13) {
                    dealerInitScore.value = 10
                } else if (lightCard == 1) {
                    dealerInitScore.value = if (dealerInitScore.value <= 21) 11 else 1;
                } else {
                    dealerInitScore.value = lightCard;
                }
                Text(
                    text = "庄家点数:${dealerInitScore.value}",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    fontStyle = FontStyle.Italic,
                    color = Color.White
                )
                Image(
                    painter = lightPainter,
                    contentDescription = "Dealer Card Back",
                    modifier = Modifier
                        .padding(top = 16.dp, end = 16.dp, bottom = 30.dp)
                        .size(100.dp)
                )
                Image(
                    painter = painterResource(id = R.drawable.card_back),
                    contentDescription = "Dealer Card Back",
                    modifier = Modifier
                        .padding(top = 16.dp, end = 16.dp, bottom = 30.dp)
                        .size(100.dp)
                )
            }
        }
    }
}


@Composable
fun generateDealerLightCard(): MutableState<Int> {
    val randomCard = remember { mutableStateOf(Random.nextInt(1, 14)) };
    Log.d("DealerLightCard", "generateDealerLightCard: ${randomCard.value} ")
    return randomCard
}


@Composable
fun DealerAskForCards(
    rememberChipValue: MutableState<Int>,
    rememberRemainingChips: MutableState<Int>,
    isDealerTurnToAskForCards: MutableState<Boolean>,
    dealerInitScore: MutableState<Int>,
    dealerCardResourceIds: MutableList<Int>,
    theDealerHasFinishedTakingTheCards: MutableState<Boolean>
) {

    if (isDealerTurnToAskForCards.value == true) {
        val context = LocalContext.current

        Log.d("DealerAskForCards", "DealerAskForCards: ${dealerInitScore.value} ")
        LaunchedEffect(Unit) {
            val baseCardScore = dealerInitScore.value
            val randomColor = Random.nextInt(1, 5) // 1-4
            val cardStr = when (randomColor) {
                1 -> "card_clubs_$baseCardScore"
                2 -> "card_diamonds_$baseCardScore"
                3 -> "card_hearts_$baseCardScore"
                4 -> "card_spades_$baseCardScore"
                else -> ""
            }
            val resId = context.resources.getIdentifier(cardStr, "drawable", context.packageName)
            dealerCardResourceIds.add(resId)
            while (dealerInitScore.value < 17) {
                addNewCard(dealerCardResourceIds, dealerInitScore, context)
            }
        }
    }

    val whetherTheDealerBustedTheCard = remember { mutableStateOf(false) }
    if (dealerInitScore.value >= 17 && dealerInitScore.value <= 21) {
        startDisplayDealerCards(dealerCardResourceIds, dealerInitScore)
        theDealerHasFinishedTakingTheCards.value = true

    } else if (dealerInitScore.value > 21) {
        startDisplayDealerCards(dealerCardResourceIds, dealerInitScore)
        Log.e("DealerAskForCards", "庄家爆牌: ${dealerInitScore.value} ")
        whetherTheDealerBustedTheCard.value = true

    }
    DealerBustedTheCard(whetherTheDealerBustedTheCard ,rememberRemainingChips , rememberChipValue)

}

@Composable
fun DealerBustedTheCard(
    whetherTheDealerBustedTheCard: MutableState<Boolean>,
    rememberRemainingChips: MutableState<Int>,
    rememberChipValue: MutableState<Int>
) {
    if (!whetherTheDealerBustedTheCard.value) return
    LaunchedEffect(Unit) {
        rememberRemainingChips.value += rememberChipValue.value
//        whetherTheDealerBustedTheCard.value = false
    }
    Box(modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(id = R.drawable.point_banker_bob_lose),
            contentDescription = "lose",
            modifier = Modifier
                .size(200.dp)
                .align(Alignment.Center)
                .padding(top = 100.dp)
        )
    }

}

@Composable
fun startDisplayDealerCards(
    dealerCardResourceIds: MutableList<Int>,
    dealerInitScore: MutableState<Int>
) {

    Box(modifier = Modifier.fillMaxSize()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .align(Alignment.TopCenter)
                .offset(y = (250).dp)
                .offset(x = (150).dp)
        ) {
            Text(
                text = "庄家点数:${dealerInitScore.value}",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                fontStyle = FontStyle.Italic,
                color = Color.White
            )
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.Center)
                .padding(0.dp)
                .offset(y = (-100).dp), horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {

            dealerCardResourceIds.forEach { resourceId ->
                Image(
                    painter = painterResource(id = resourceId),
                    contentDescription = "deal",
                    modifier = Modifier
                        .size(100.dp)
                        .padding(top = 0.dp)
                )
            }
            // 只渲染当前索引及之前的卡片
//                dealerCardResourceIds.take(currentIndex.value).forEach { resourceId ->
//                    Image(
//                        painter = painterResource(id = resourceId),
//                        contentDescription = "deal",
//                        modifier = Modifier
//                            .size(100.dp)
//                            .padding(top = 10.dp)
//                    )
//                }
        }
    }

}

//@Composable
private fun addNewCard(
    cardResourceIds: MutableList<Int>,
    playerCurrentScore: MutableState<Int>,
    context: android.content.Context
) {
    val baseCardScore = Random.nextInt(1, 14) // 1-13
    var result = playerCurrentScore.value

    // 根据新添加的卡片更新分数
    if (baseCardScore >= 11) {
        result += 10
    } else if (baseCardScore == 1) {
        if (result + 11 <= 21) {
            result += 11
        } else {
            result += 1
        }
    } else {
        result += baseCardScore
    }

    playerCurrentScore.value = result

    // 根据新添加的卡片确定资源 ID
    val randomColor = Random.nextInt(1, 5) // 1-4
    val cardStr = when (randomColor) {
        1 -> "card_clubs_$baseCardScore"
        2 -> "card_diamonds_$baseCardScore"
        3 -> "card_hearts_$baseCardScore"
        4 -> "card_spades_$baseCardScore"
        else -> ""
    }
    val resId = context.resources.getIdentifier(cardStr, "drawable", context.packageName)
    Log.d("addNewCard", "addNewCard: $resId ")

    if (resId != 0) {
        Log.e("addNewCard", "addNewCard: $cardStr ")
        cardResourceIds.add(resId)
    }
}